/*
 * @Description:
 * @Author: wangqian
 * @LastEditors: wangqian
 * @Date: 2021-06-22 20:40:48
 * @LastEditTime: 2021-06-22 21:53:12
 */

/**
 * @description: 根据id获取节点
 * @param {string} key
 * @param {string} val
 * @param {any} data
 * @return {*}
 */
export const getNodeById = (key: string, val: string, data: any[]): any => {
  let hasFound = false, // 表示是否有找到id值
    result = null;
  const fn = function (data: any[]) {
    if (Array.isArray(data) && !hasFound) {
      // 判断是否是数组并且没有的情况下，
      data.forEach(item => {
        if (item[key] === val) {
          // 数据循环每个子项，并且判断子项下边是否有id值
          result = item; // 返回的结果等于每一项
          hasFound = true; // 并且找到id值
        } else if (item.children) {
          fn(item.children); // 递归调用下边的子项
        }
      });
    }
  };
  fn(data); // 调用一下
  return result;
};
type TreeProps = {
  children?: Array<TreeProps> | null;
  [key: string]: any;
};
type CallbackState = (data: TreeProps) => void;
// 深度优先遍历 tree
export const depthEach = (treeList: Array<TreeProps>, callback: CallbackState) => {
  treeList.forEach(item => {
    const map = (data: TreeProps): void => {
      callback && callback(data);
      data.children && data.children.forEach((child: TreeProps) => map(child));
    };
    map(item);
  });
};

type List2treeItem = {
  code: string;
  children: any;
  parentCode: string;
  attributes?: any;
};

type List2treeCallback = (data: TreeProps) => TreeProps;
// list转tree
export const list2tree = (list: any, parentCode: any, callback: List2treeCallback) => {
  try {
    const tmp: any = {};
    list.forEach((item: List2treeItem) => {
      item.children = [];
      tmp[item.code] = callback(item);
    });

    return list.filter((item: List2treeItem) => {
      if (item.parentCode !== parentCode) {
        tmp[item.parentCode].children.push(item);
        return false;
      }
      return true;
    });
  } catch (err) {
    console.log('list2tree err=', err);
    return list;
  }
};
